package top.catblog.security.securityspringmvc.service;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.catblog.security.securityspringmvc.model.AuthenticationRequest;
import top.catblog.security.securityspringmvc.model.UserDto;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 毕晓杰602105
 * @Date 2021/3/14 16:51
 * @Version 1.0
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        //校验参数是否为空
        if (authenticationRequest == null
                || StringUtils.isEmpty(authenticationRequest.getUsername())
                || StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw  new RuntimeException("账号和密码为空");
        }

        // 根据账号密码去查询数据库
        UserDto user = getUserDto(authenticationRequest.getUsername());
        // 判断用户是否为空
        if (user == null) {
            throw  new RuntimeException("查询不到该账户");
        }

        // 校验密码
        if (!authenticationRequest.getPassword().equals(user.getPassword())){
            throw  new RuntimeException("账号或密码错误");
        }
        // 认证通过,返回用户信息
        return user;
    }

    // 根据账号查询用户信息

    private UserDto getUserDto(String userName){
        return userDtoMap.get(userName);
    }

    private Map<String,UserDto> userDtoMap = new HashMap<>();
    {
        userDtoMap.put("zhangsan",new UserDto("1","zhangsan","123","张三","123456"));
    }
}
